package com.xixi.service;
import com.xixi.model.RegionState;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MyService{
    private static Logger logger = LoggerFactory.getLogger(MyService.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedDelay = 10000)
    public CSVParser getCSV() throws IOException {
        RestTemplate restTemplate = new RestTemplate();
        String uri = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Mobile Safari/537.36");
        RequestEntity<Void> requestEntity = RequestEntity.get(URI.create(uri)).headers(requestHeaders).build();
        ResponseEntity<Resource> exchange = restTemplate.exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();
        logger.info("数据长度：{}", body.contentLength());
        logger.info("The time is now {}", dateFormat.format(new Date()));

        Reader reader = new InputStreamReader(body.getInputStream());
        CSVParser records = CSVParser.parse(reader, CSVFormat.DEFAULT);
        return records;
    }

    //解析csv文件-->按国家区分
    public List<RegionState> getRegionStates(String str) throws IOException {
        CSVParser records = getCSV();
        List<RegionState> res = new LinkedList<>();
        int i = 0;
        for (CSVRecord record: records) {
            i++;
            if(i == 1)
                continue;
            String region = record.get(0);
            String country = record.get(1);
            int num1 = Integer.parseInt(record.get(record.size()-1));
            int num2 = num1 - Integer.parseInt(record.get(record.size()-2));
            if(country.equals(str))
                res.add(new RegionState(region, country, num1, num2));
        }
        return res;
    }

    //合并同一国家
    public Map<String, List<RegionState>> addAllRegion() throws IOException {
        CSVParser records = getCSV();
        Map<String, List<RegionState>> map = new HashMap<>();
        int i = 0;
        for(CSVRecord record : records) {
            i++;
            if(i == 1)
                continue;
            String region = record.get(0);
            String country = record.get(1);
            int num1 = Integer.parseInt(record.get(record.size()-1));
            int num2 = num1 - Integer.parseInt(record.get(record.size()-2));
            if(map.containsKey(country))
            {
                List<RegionState> regionStates = map.get(country);
                regionStates.add(new RegionState(region, country, num1, num2));
            }else
            {
                List<RegionState> list = new LinkedList<>();
                list.add(new RegionState(region, country, num1, num2));
                map.put(country, list);
            }

        }
        return map;
    }

    public List<RegionState> getNum() throws IOException {
        Map<String, List<RegionState>> listMap = addAllRegion();
        List<RegionState> list = new LinkedList<>();
        Iterator<String> iterator = listMap.keySet().iterator();
        while(iterator.hasNext())
        {
            String country = iterator.next();
            List<RegionState> list1 = listMap.get(country);
            int num1 = 0;
            int num2 = 0;
            for(RegionState state : list1)
            {
                num1 += state.getLatestTotalCase();
                num2 += state.getDiffFromPrevDay();
            }
            list.add(new RegionState(null, country, num1, num2));
        }
        return list;
    }

}
